package com.andox.fn.inf.rpc.rest.filter;

import java.util.Set;
import java.util.stream.Collectors;

import com.andox.fn.inf.rpc.rest.RpcRequest;
import com.andox.fn.inf.rpc.rest.RpcResponse;
import com.andox.fn.inf.rpc.rest.ResponseCodes;
import com.andox.fn.inf.rpc.rest.config.MethodConfig;
import com.andox.fn.inf.rpc.rest.util.IfNullUtil;

/**   
 * @ClassName:   ServiceMethodExcludeFilter   
 * @author:      Andox
 * @date:        2019年8月2日 下午6:11:04   
 *     
 */
public class ExcludeFilter implements Filter {
	
	private volatile Set<String> excludeMethodSet;
	
	@Override
	public RpcResponse invoke(Invoker nextInvoker, RpcRequest request) {
		if (excludeMethodSet == null) {
			Set<String> excludes = IfNullUtil.ifNull(nextInvoker.getConfig().getMethodConfigs())
					.stream()
						.filter(MethodConfig::isExclude)
						.map(MethodConfig::getName)
					.collect(Collectors.toSet());
			this.excludeMethodSet = excludes;
		}
		
		if (excludeMethodSet.contains(request.getMethod())) {
			String msg = String.format("the method [%s.%s] do not exported , please contact to devoloper of the server.", 
					nextInvoker.getConfig().getInterfaceClass().getName(), request.getMethod());
			return RpcResponse.failed(request.getOpaque(), ResponseCodes.METHOD_DO_NOT_EXPORT_ERROR, msg);
		}
		
		return nextInvoker.invoke(request);
	}
}
